package com.harmony.pilot.agent.controller;

import com.harmony.pilot.agent.model.AgentResponse;
import com.harmony.pilot.agent.model.Conversation;
import com.harmony.pilot.agent.model.ConversationContext;
import com.harmony.pilot.agent.service.AgentCoreService;
import com.harmony.pilot.agent.service.ConversationManager;
import com.harmony.pilot.common.dto.RestResult;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/agent")
@RequiredArgsConstructor
public class AgentController {
    
    private final AgentCoreService agentCoreService;
    private final ConversationManager conversationManager;
    
    @PostMapping("/chat")
    public RestResult<AgentResponse> chat(@RequestBody ChatRequest request) {
        log.info("Received chat request for session: {}", request.getSessionId());
        
        // 更新上下文
        if (request.getContext() != null) {
            conversationManager.updateContext(
                request.getSessionId(), 
                request.getContext()
            );
        }
        
        AgentResponse response = agentCoreService.processUserMessage(
            request.getSessionId(),
            request.getMessage()
        );
        
        return RestResult.success(response);
    }
    
    @GetMapping("/conversation/{sessionId}")
    public RestResult<Conversation> getConversation(@PathVariable String sessionId) {
        return RestResult.success(
            conversationManager.getConversation(sessionId)
        );
    }
    
    @DeleteMapping("/conversation/{sessionId}")
    public RestResult<String> clearConversation(@PathVariable String sessionId) {
        conversationManager.clearConversation(sessionId);
        return RestResult.success("Conversation cleared");
    }
    
    @PostMapping("/conversation/{sessionId}/context")
    public RestResult<String> updateContext(
            @PathVariable String sessionId,
            @RequestBody ConversationContext context) {
        conversationManager.updateContext(sessionId, context);
        return RestResult.success("Context updated");
    }
    
    @GetMapping("/health")
    public RestResult<String> health() {
        return RestResult.success("Agent Service is running");
    }
    
    @Data
    public static class ChatRequest {
        private String sessionId;
        private String message;
        private ConversationContext context;
    }
}

